﻿
namespace BadJokeProject.Web
{
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using BadJokeProject.Web.Model;
    using System.Xml.Linq;

    // TODO: Create methods containing your application logic.
    [EnableClientAccess()]
    public class BadJokeDomainService : DomainService
    {

        [Query(IsComposable = false)]
        public IEnumerable<BadJokeItem> GetBadJokeItems()
        {
            XDocument data = XDocument.Load(ConstStrings.DataFilePath);
            List<BadJokeItem> result = new List<BadJokeItem>();
            foreach (var item in data.Descendants("BadJokeItem"))
            {
                var badJoke = new BadJokeItem
                {
                    ID = item.Element("ID").Value,
                    Title = item.Element("Title").Value,
                    Content = item.Element("Content").Value
                };
                result.Add(badJoke);
            }
            return result.AsEnumerable<BadJokeItem>();
        }

        [Invoke]
        public void InsertNewBadJokeItem(BadJokeItem newItem)
        {
            XDocument data = XDocument.Load(ConstStrings.DataFilePath);
            var lastIndex = data.Descendants("BadJokeItem").Last().Element("ID").Value;
            var newID = Convert.ToInt32(lastIndex) + 1;
            data.Descendants("BadJokes").First().Add(
                new XElement("BadJokeItem",
                    new XElement("ID", newID.ToString()),
                    new XElement("Title", newItem.Title),
                    new XElement("Content", newItem.Content)));
            data.Save(ConstStrings.DataFilePath, SaveOptions.DisableFormatting);
        }

        [Invoke]
        public bool VerifyXiaoBai(string name, string password)
        {
            return name.Equals("小白") && password.Equals("小白");
        }
    }
}


